<template>
  <div class="login-box">
    <div class="login-logo">
      <!-- <SvgIcon name="logo" /> -->
      <!-- <img :src="logo" alt="" @click="addUser" /> -->
      <h1>后台管理系统</h1>
    </div>
    <a-form layout="horizontal"
            :model="formInline"
            @submit="handleSubmit">
      <a-form-item>
        <a-input v-model:value.trim="formInline.phone"
                 size="large"
                 placeholder="请输入账号">
          <template #prefix>
            <user-outlined type="user" />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item>
        <div class="yzm">
          <a-input v-model:value.trim="formInline.yzm"
                   size="large"
                   type="yzm"
                   placeholder=""
                   autocomplete="new-yzm">
            <template #prefix>
              <lock-outlined type="user" />
            </template>
          </a-input>
          <a-button type="primary"
                    :disabled="yzmDisabled"
                    :loading="yzmLoading"
                    @click="handleGetCode">{{ yzmText }}</a-button>
        </div>
      </a-form-item>
      <SmileOutlined :rotate="180" />
      <a-form-item>
        <a-button type="primary"
                  html-type="submit"
                  size="large"
                  :loading="loading"
                  block>
          登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref } from 'vue'
import { message } from 'ant-design-vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
// import md5 from 'blueimp-md5'
// ~@/assets/logo.png
import { useRoute, useRouter } from 'vue-router'
import { useStore } from '@/store'

import { SvgIcon } from '@/components/svg-icon'
import commonApi from '@/api/common'
import config, { MODE } from '@/config'
import logo from '@/assets/images/logo.png'
import userApi from '@/api/bg_user'

export default defineComponent({
  name: 'Login',
  components: { UserOutlined, LockOutlined, SvgIcon },
  setup() {
    const state = reactive({
      logo,
      loading: false,
      yzmLoading: false,
      yzmText: '获取验证码',
      yzmDisabled: false,
      formInline: {
        phone: MODE === 'dev' ? '15262596631' : '',
        yzm: ''
      }
    })

    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const addUser = async () => {
      //添加系统账号
      if (MODE === 'dev') {
        let res = await userApi.addUser({ phone: state.formInline.phone })
        console.log('%c 🍢 res: ', 'font-size:20px;background-color: #465975;color:#fff;', res)
      }
    }
    let t = ref<any>(null)

    const handleGetCode = async () => {
      if (!config.validatePhoneRule.test(state.formInline.phone)) {
        message.warning('请输入正确的手机号码')
        return
      }
      state.yzmLoading = true
      // let checkUserRes = await userApi.checkUser({ phone: state.formInline.phone })
      // if (!checkUserRes.count) {
      //   message.warning('暂无此管理员')
      //   return
      // }
      // if (t.value) return
      state.yzmLoading = true
      let res = await commonApi.getYzm({ mobile: state.formInline.phone })
      console.log('%c 🍱 res: ', 'font-size:20px;background-color: #3F7CFF;color:#fff;', res)
      state.yzmLoading = false
      let count = 60
      if (res.retCode == 0) {
        state.yzmDisabled = true
        t.value = setInterval(() => {
          count--
          state.yzmText = count + '秒重新获取'
          if (count <= 0) {
            clearInterval(t.value)
            state.yzmLoading = false
            state.yzmDisabled = false
            state.yzmText = '重新获取'
            t.value = null
          }
        }, 1000)
      } else {
        message.warning(res.retMsg)
      }
    }

    const handleSubmit = async () => {
      // router.replace('/bordereaux/discountCoupon')
      // return
      const { phone, yzm } = state.formInline
      if (phone.trim() == '' || yzm.trim() == '') return message.warning('手机号或验证码不能为空！')
      message.loading('登录中...', 0)
      state.loading = true
      console.log(state.formInline)
      const params = {
        phone: phone,
        smsCode: yzm
      }
      // params.yzm = md5(yzm)

      const result = await store.dispatch('user/login', params).finally(() => {
        state.loading = false
        message.destroy()
      })

      //@ts-ignore
      // const result = await userApi.yzmLogin(params)
      state.loading = false
      message.destroy()

      console.log('%c 🍫 result: ', 'font-size:20px;background-color: #EA7E5C;color:#fff;', result)
      if (result.token) {
        const toPath = decodeURIComponent((route.query?.redirect || '/') as string)
        message.success('登录成功！')
        router.replace(toPath).then((_) => {
          if (route.name == 'login') {
            router.replace('/')
          }
        })
      } else {
        message.info(result.retMsg)
      }
    }
    return {
      ...toRefs(state),
      addUser,
      handleSubmit,
      handleGetCode
    }
  }
})
</script>

<style lang="scss" scoped>
.yzm {
  display: flex;
  justify-content: space-between;

  .ant-btn {
    height: 40px;
    margin-left: 20px;
  }
}

.login-box {
  display: flex;
  width: 100vw;
  height: 100vh;
  padding-top: 240px;
  background: url('@/assets/login.svg');
  background-size: 100%;
  flex-direction: column;
  align-items: center;

  .login-logo {
    display: flex;
    margin-bottom: 30px;
    align-items: center;

    .svg-icon {
      font-size: 48px;
    }

    img {
      height: 60px;
    }

    h1 {
      margin-bottom: 0;
      margin-left: 10px;
    }
  }

  ::v-deep(.ant-form) {
    width: 400px;

    .ant-col {
      width: 100%;
    }

    .ant-form-item-label {
      padding-right: 6px;
    }
  }
}
</style>
